import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import electron from 'vite-plugin-electron'
import electronRenderer from 'vite-plugin-electron-renderer'
import path from 'path'
import fs from 'fs'

export default defineConfig({
  plugins: [
    vue(),
    electron({
      entry: 'electron/main.ts',
      onstart(options) {
        options.startup(['.', '--no-sandbox'])
      },
      vite: {
        build: {
          outDir: 'dist-electron',
          rollupOptions: {
            input: {
              main: path.resolve(__dirname, 'electron/main.ts'),
              preload: path.resolve(__dirname, 'electron/preload.ts')
            },
            external: ['electron'],
            output: {
              format: 'cjs',
              entryFileNames: '[name].js'
            }
          },
          // 关键配置：确保 config.json 被复制到输出目录
          assetsInclude: ['config.json'],
          copyPublicDir: false // 禁用默认的 public 目录复制
        }
      },
      // 新增：打包完成后自动复制 config.json
      closeBundle() {
        const outDir = path.resolve(__dirname, 'dist')
        const electronOutDir = path.resolve(__dirname, 'dist-electron')
        fs.copyFileSync(
          path.resolve(__dirname, 'config.json'),
          path.join(outDir, 'config.json')
        )
        fs.copyFileSync(
          path.resolve(__dirname, 'config.json'),
          path.join(electronOutDir, 'config.json')
        )
      }
    }),
    electronRenderer()
  ],
  build: {
    outDir: 'dist',
    emptyOutDir: true,
    rollupOptions: {
      input: {
        index: path.resolve(__dirname, 'index.html')
      },
      // 确保 config.json 不被前端构建处理
      external: ['../config.json']
    }
  },
  publicDir: false, // 完全禁用 public 目录
  base: './',
  optimizeDeps: {
    exclude: ['electron'],
    include: ['pinia']
  },
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true
      }
    },
    port: 5173,
    strictPort: true
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  }
})